var vue = new Vue({
    el: "#main",
    data() {
        return {
            hls: null,
            active: 1,
            placeList: [],
            gridList: [],
            sonList: [],
            monitorCommunityList: [], //监控社区数据的列表
            gridTotal: '',
            categoryTotal: '',
            placeTotal: '',
            monitorTotal: "", //监控总数
            flvPlayer: null, //监控数据
            isShowVideo: false, //是否显示监控的dia
            isShowTYVideo: false, //是否显示监控的dia
            isShowTYVideoLoading: false, //是否显示监控的dia
            TYtimer: null, //天翼监控定时器
            TYUrl: '', //天翼监控的url
            isLoading: false, //是否显示监控画面的loading
            player: null, //监控播放对象
            monitorDetail: {}, //监控详情
            type: '', //监控类型，vcp是天翼的，
            num: '',
            numtimer: null, //监控计时器
            searchVal: '', //监控搜索字段
            searchLoading: false, //设否正在搜索
            searchflag: false, //是否是搜索
            isEmpty: false, //是否为空
        }
    },
    created() {
        // 判断是否是监控页面过来的
        if (getRequest().type == 'monitor') {
            this.active = 3
        }
    },
    mounted() {
        this.getPlaceList()
        this.getGridList()
        this.getCommunityList()
    },
    destroy() {
        if (this.TYtimer) {
            clearTimeout(this.TYtimer)
            this.TYtimer = null
        }
    },
    methods: {
        // 网格下社区查看or收起
        unwindBtn(id) {
            this.gridList.map(item => {
                if (id == item.dept_id) {
                    this.sonList = item.place
                    item.flag = !item.flag
                } else {
                    item.flag = false
                }
            })
        },

        // 监控下社区查看or收起
        unwindBtnMonitor(id) {
            this.monitorCommunityList.map(item => {
                if (id == item.id) {
                    this.sonList = item.place
                    if (item.flag) {
                        item.category.forEach(el => {
                            el.flag = false
                        })
                    }
                    item.flag = !item.flag
                } else {
                    item.flag = false
                }
            })
        },
        // 点击监控类型展开里面的内容
        unwindBtnMonitorType(item, type) {
            // console.log(item, type)
            item.category.forEach(el => {
                if (el.category_id == type.category_id) {
                    type.flag = !type.flag
                } else {
                    el.flag = false
                }
            })
        },
        // 点击网格-社区下的网格员跳转到场所列表
        goPlaceList(id, type) {
            window.location.href = "placeList.html?id=" + id + '&type=' + type
        },
        // 点击行业下场所分类，跳转到场所列表
        goPlaceListCate(id, type) {
            window.location.href = "placeList.html?cate_id=" + id + '&type=' + type
        },
        // 行业下场所分类列表
        getPlaceList() {
            ajax({
                url: formal + '/place/category',
                type: 'GET',
                success: (res) => {
                    this.placeList = res.data.list
                    this.categoryTotal = res.data.total
                },
                error: (err, res, add) => {
                    // console.log(res,add)
                    // console.log(err.status)
                    // alert(err.message)
                    // alert(JSON.stringify(add))
                }
            })
        },
        // 网格下社区和网格员列表
        getGridList() {
            ajax({
                url: formal + '/place/get-grids',
                type: 'GET',
                success: (res) => {
                    let newItem = {}
                    res.data.list.map(item => {
                        newItem = item
                        newItem.flag = false
                    })
                    this.gridTotal = res.data.total
                    this.gridList = res.data.list
                    this.placeTotal = res.data.place_total
                },
                error: (res) => {
                    localStorage.removeItem("token")
                    if (res.responseJSON.name == "Unauthorized") {
                        window.location.href = "login.html"
                    }
                }
            })
        },
        // 获取监控社区列表
        getCommunityList() {
            ajax({
                url: formal + '/monitoring/get-monitoring?keywords=' + this.searchVal,
                type: 'GET',
                success: (res) => {
                    console.log(res)
                    this.searchLoading = false
                    res.data.list.forEach(item => {
                        item.flag = false
                        item.category.forEach(el => {
                            el.flag = false
                        });
                    })
                    console.log(res.data.list)
                    this.monitorTotal = res.data.total
                    this.monitorCommunityList = res.data.list
                },
                error: () => {
                    this.searchLoading = false
                }
            })
        },
        search() {
            if (this.searchLoading) {
                return;
            }
            if (this.searchVal) {
                this.searchflag = true
            } else {
                this.searchflag = false
            }
            this.searchLoading = true
            this.getCommunityList()
        },
        reset() {
            if (this.searchLoading) {
                return;
            }
            this.searchVal = ''
            this.searchflag = false
            this.searchLoading = false
            this.getCommunityList()
        },
        //点击监控按钮获取监控详情
        handleMonitorMarker(id) {
            // this.isShowVideo = true
            // this.isLoading = true
            let showLoading = vant.Toast.loading({
                message: '加载中...',
                forbidClick: true,
            });
            ajax({
                url: formal + '/monitoring/get-monitoring-view',
                type: 'GET',
                data: {
                    id: id
                },
                success: (res) => {
                    if (showLoading) showLoading.close()
                    this.monitorDetail = res.data
                    this.type = res.data.type
                    if (!this.monitorDetail.url) {
                        this.isShowVideo = false
                        this.isLoading = false
                        this.$message.closeAll()
                        return this.$message.error("监控视频地址不存在")
                    }
                    if (this.type == 'vcp') {
                        this.isShowTYVideo = true
                        this.TYUrl = 'http://vcp.21cn.com/metaplayer/static/template/latest/player.html?appId=94f881&count=1&streamSrc=' + this.monitorDetail.url
                    } else {
                        this.isShowVideo = true
                    }
                    this.showVideo()
                },
                error: () => {
                    this.isShowVideo = false
                    this.isLoading = false
                    if (showLoading) showLoading.close()
                }
            })
        },
        callback(a, b) {
            console.log(a, b)
            if (this.num == 'end') {
                if (this.numtimer) {
                    clearTimeout(this.numtimer)
                    this.numtimer = null
                }
                return
            }
            if (!this.num) {
                this.num = b
                if (!this.numtimer) {
                    this.numtimer = setTimeout(() => {
                        if (!this.num) {
                            this.isShowVideo = false
                            this.isLoading = false
                            this.player.destroy();
                            this.$message.closeAll()
                            this.num = 'end'
                            return this.$message.error("播放失败")
                        }
                    }, 9000)
                }
            } else {
                if (this.numtimer) {
                    clearTimeout(this.numtimer)
                    this.numtimer = null
                }
            }

        },
        cfKbs(a) {
            if (a.currentKbps) {
                if (this.numtimer) {
                    clearTimeout(this.numtimer)
                    this.numtimer = null
                }
            }
        },
        //点击详情摄像头图标显示监控
        showVideo() {
            if (this.numtimer) {
                clearTimeout(this.numtimer)
                this.numtimer = null
            }
            if (this.type == 'vcp') {
                this.isShowTYVideoLoading = true
                // $("#my-player").hide()
                // $("#my-player1").show()
                // // this.monitorDetail.url = 'http://222.190.127.42:7086/live/cameraid/1000001%249/substram/1000000008.m3u8'
                // this.isLoading = false
                // this.num = ''
                // // this.player = new WasmPlayer(null, 'my-player1')
                // this.player = new WasmPlayer(null, 'my-player1', this.callback, {
                //     cfKbs: this.cfKbs
                // })
                // // 调用播放
                // this.player.play(this.monitorDetail.url, 1)

                const player1Api = new MpIframe(document.querySelector('#TYplayer'));
                player1Api.on('isFirstFrame', () => {
                    if (this.TYtimer) {
                        clearTimeout(this.TYtimer)
                        this.TYtimer = null
                    }
                    this.isShowTYVideoLoading = false
                })
                this.TYtimer = setTimeout(() => {
                    if (this.isShowTYVideoLoading) {
                        this.$message.error("监控播放异常")
                        clearTimeout(this.TYtimer)
                        this.TYtimer = null
                        this.TYUrl = ''
                        this.isShowTYVideo = false
                        this.isShowTYVideoLoading = false
                    }
                }, 10000)
                return
            }


            if (this.monitorDetail.url.indexOf("ws://") !== -1 || this.monitorDetail.url.indexOf("wss://") !== -1) {
                this.isShowVideo = true
                // this.isLoading = true
                $("#my-player").hide()
                this.player = new window.JSPlugin({
                    szId: 'my-player1', //节点id
                    szBasePath: '/static/h5player', //插件路径
                    openDebug: false,
                })
                let playURL =
                    this.monitorDetail.url
                this.player.JS_Play(playURL, {
                    playURL,
                    mode: 0 // 1为高级模式，0为普通模式
                }, 0).then(() => {
                    // 播放成功
                    this.isLoading = false
                }, e => {
                    // 播放失败
                    this.$message({
                        message: '播放失败',
                        type: 'error',
                        duration: 3000
                    });
                })
            } else if (this.monitorDetail.url.indexOf(".m3u8") !== -1) {
                $("#my-player1").hide()
                $("#my-player").show()
                this.isShowVideo = true
                this.isLoading = true
                this.player = document.getElementById("my-player");
                if (Hls.isSupported()) {
                    this.hls = new Hls();
                    this.hls.loadSource(this.monitorDetail.url);
                    this.hls.attachMedia(this.player);
                    this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
                        this.player.play();
                        this.isLoading = false
                    });
                } else if (this.player.canPlayType("application/vnd.apple.mpegurl")) {
                    this.player.src = this.monitorDetail.url;
                    this.player.addEventListener("loadedmetadata", () => {
                        this.player.play();
                        this.isLoading = false
                    });
                }
                return;
                this.isShowVideo = true
                // this.isLoading = true
                $("#my-player").hide()

                var videoObject = {
                    container: '#my-player1', //容器的ID或className
                    live: true, //指定为直播
                    autoplay: true,
                    volume: 0.001,
                    type: "hls",
                    mouseWheelVolume: 0,
                    keyVolume: 0,
                    playbackrateList: [1],
                    plug: 'hls.js', //设置使用hls插件
                    video: this.monitorDetail.url //视频地址
                }
                this.player = new ckplayer(videoObject);

                // var videoObject = {
                //     container: '#my-player1', //容器的ID或className
                //     live: true, //指定为直播
                //     autoplay: true,
                //     volume: 0.001,
                //     type: "hls",
                //     mouseWheelVolume: 0,
                //     keyVolume: 0,
                //     playbackrateList: [1],
                //     plug: 'hls.js', //设置使用hls插件
                //     video: this.monitorDetail.url //视频地址
                // }
                // this.player = new ckplayer(videoObject);
                this.player.play(() => {
                    this.isLoading = false
                })
                this.player.error(() => {
                    this.$message({
                        message: '播放失败',
                        type: 'error',
                        duration: 3000
                    });
                    this.closeVodeo()
                })
            } else {
                if (flvjs.isSupported()) {
                    this.isShowVideo = true
                    // this.isLoading = true
                    $('.ub-showVideo').show()
                    this.showDetail = false
                    let videoElement = document.getElementById('my-player');
                    this.player = flvjs.createPlayer({
                        type: 'flv',
                        isLive: true,
                        url: this.monitorDetail.url, //<==自行修改
                    }, {
                        enableWorker: false, //不启用分离线程
                        enableStashBuffer: false, //关闭IO隐藏缓冲区
                        reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
                        autoCleanupSourceBuffer: true //自动清除缓存
                    });
                    this.player.attachMediaElement(videoElement);
                    this.player.load(); //加载
                    setTimeout(() => {
                        document.getElementById('my-player').onplay = () => {
                            this.isLoading = false
                        };
                    }, 300)
                } else {
                    alert("ios暂不支持此格式视频播放")
                    this.showDetail = false
                }
            }


        },
        // 关闭监控
        closeVodeo() {
            this.isShowVideo = false
            this.isLoading = false
            if (this.numtimer) {
                clearTimeout(this.numtimer)
                this.numtimer = null
            }
            $('.ub-showVideo').hide()
            if (this.type == 'vcp') {
                if (this.TYtimer) {
                    clearTimeout(this.TYtimer)
                    this.TYtimer = null
                }
                this.TYUrl = ''
                this.isShowTYVideo = false
                this.isShowTYVideoLoading = false
                return
            }
            if (this.monitorDetail.url.indexOf("ws://") !== -1 || this.monitorDetail.url.indexOf("wss://") !== -1) {
                this.player.JS_Stop()
            } else if (this.monitorDetail.url.indexOf(".m3u8") !== -1) {

                // $('#video1').children('#my-player').remove()
                // $('#video1').append('<video id="my-player" style="width: 100%;" preload="auto" muted autoplay controls style="border: 1px solid red;">< source src = "" ></video>')
                // this.player = null
                this.hls.destroy();
                // this.player.destroy();
                // this.player.remove()
            } else {
                this.player.destroy()
            }

        },
    }
})